<template>
	<view class="loginLayout pageBg">
		<view class="title-box">
			<view class="avatar">
				<image src="../../static/image/user/user.jpg" mode="aspectFill"></image>
			</view>
			<view class="title">用户登录</view>
		</view>
		<view class="login-form">
				<form @submit="login">
					<up-subsection 
						:list="sectionList" 
						:current="current"
						activeColor="#f56c6c"
						@change="sectionChange"
						>
						</up-subsection>
					<view v-if="current == 0">
						<view class="uni-form-item">
							<view class="phone">
								<uni-icons type="contact" size="30" color="#FF4D4F"></uni-icons>
								<input v-model="loginForm.phone" class="input" type="text" placeholder="请输入电话" maxlength="20" />
							</view>
						</view>
						<view class="tip" v-if="tip.phone !== ''">{{tip.phone}}</view>
						<view class="uni-form-item vertify-box">
							<view class="vertify">
								<uni-icons type="checkbox" size="30" color="#FF4D4F"></uni-icons>
								<input v-model="loginForm.vcode" class="input" type="text" placeholder="请输入验证码" maxlength="20" />
							</view>
							<button class="vcode-btn" @click="getVCode" plain="true" :disabled="vcodeSanding">
								{{ vcodeSanding ? `${vcodeCountdown}s后重发` : '发送验证码' }}
							</button>
						</view>
						<view class="tip"  v-if="tip.vcode !== ''">{{tip.vcode}}</view>
					</view>
					<view v-else-if="current == 1">
						<view class="uni-form-item">
							<view class="phone">
								<uni-icons type="contact" size="30" color="#FF4D4F"></uni-icons>
								<input v-model="loginForm.phone" class="input" type="text" placeholder="请输入电话" maxlength="20" />
							</view>
						</view>
						<view class="tip"  v-if="tip.phone !== ''">{{tip.phone}}</view>
						<view class="uni-form-item">
							<view class="password">
								<uni-icons type="locked" size="30" color="#FF4D4F"></uni-icons>
								<input v-model="loginForm.password" class="input" type="text" placeholder="请输入密码" maxlength="20" />
							</view>
						</view>
						<view class="tip" v-if="tip.password !== ''">{{tip.password}}</view>
					</view>
					
					<view class="uni-btn-v">
						<button class="login-btn" @click="login" >登录</button>
					</view>
					
				</form>
		</view>


		
	
	</view>
</template>

<script setup>
import { onBeforeUnmount, reactive, ref } from 'vue';
import { appUrl } from '../../main';
  
const sectionList = ref(['验证码登录', '密码登录']);  
const current = ref(0);  
const sectionChange = (index) => {
	current.value = index
}

//变量
const active = ref(0)
const loginForm = reactive({
	phone: "",
	password: "",
	vcode: "",				//验证码
})
const tip = reactive({
	phone: "",
	password: "",
	vcode: "",
})
const vcodeSanding= ref(false)
const vcodeCountdown = ref(0)
let timer = null
	
//函数
const getVCode = async () => {
	if(vcodeSanding.value) return
	if(validatePhone()){
		vcodeSanding.value = true
		vcodeCountdown.value = 60
		try{
			uni.request({
			    url: appUrl+'/VCode',
			    data: {
			        phone: loginForm.phone
			    },
				method: "post"
			}).then((res) => {
				if(res.data.status == 200){
					loginForm.vcode = res.data.data
					startCountdown()
				}else{
					codeSanding.value = false
					vcodeCountdown.value = 0
					throw new Error('发送失败，请检查网络连接或稍后再试');
				}
			})
		}catch(error){
			console.error('发送验证码失败:', error);
			uni.showToast({
				title: '发送失败，请稍后再试',
				icon: 'fail'
			});
		}finally{
			if (!vcodeCountdown.value) {
			    stopCountdown();
			}
		}
	}
}
const startCountdown = () => {
  timer = setInterval(() => {
    if (vcodeCountdown.value > 0) {
      vcodeCountdown.value--;
    } else {
      stopCountdown();
    }
  }, 1000);
};

const stopCountdown = () => {
  clearInterval(timer); // 清除定时器
  timer = null;
  vcodeSanding.value = false; // 使按钮可再次点击
};

const login = () => {
	if(validation()){
		
		try{
			uni.request({
			    url: appUrl+'/users/login',
			    data: loginForm,
				method: "post"
			}).then((res) => {
				if(res.data.status == 200){
					uni.showToast({
						title: '成功登录',
						duration: 1000
					});
					uni.setStorageSync('token', res.data.data);
					uni.reLaunch({
						url:"/pages/UserView/UserView"
					})
				}else{
					console.log(res.data);
					uni.showToast({
						title: '输入错误',
						icon: "error",
						duration: 1000,
					});

				}
			})
		}catch(error){
			uni.showToast({
				title: '网络错误',
				icon: "error",
				duration: 1000,
			});
		}
		
	}else{
		uni.showToast({
			title: '失败',
			icon: "error",
		})
	}
}
const validation = () => {
	return validatePhone() && (current.value === 0 ? validateCode() : validatePassword())
}
const validateCode = () => {
	const codeRegex = /^\d{4,}$/
	if(loginForm.vcode === ""){
		tip.vcode = "验证码不能为空"
		return false
	}else if(codeRegex.test(loginForm.vcode)){
		tip.vcode = ""
		return true
	}else{
		tip.vcode = "验证码格式不正确"
		return false
	}
}
const validatePassword = () => {
	const passwordRegex = /^[^\s]{1,20}$/
	
	if(loginForm.password === ""){
		tip.password = "密码不能为空"
		return false
	}else if(passwordRegex.test(loginForm.password)){
		tip.password = ""
		return true
	}else{
		tip.password = "密码格式不正确"
		return false
	}
}
const validatePhone = () => {
	const phoneRegex = /^1[3-9]\d{9}$/;
	if(loginForm.phone === ""){
		tip.phone = "手机号不能为空"
		return false
	}else if (phoneRegex.test(loginForm.phone)) {
		tip.phone = ""
		return true
	  // 进行下一步操作，例如提交表单
	} else {
		tip.phone = "手机号格式不正确"
		return false
	  // 提示用户输入正确的手机号
	}
}

//钩子
onBeforeUnmount(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style lang="scss" scoped>
.loginLayout{
	height: 100vh;
	.title-box{
		display: flex;
		align-items: center;
		justify-content: center;
		flex-direction: column;
		padding: 200rpx 50rpx;
		.avatar{
			width: 160rpx;
			height: 160rpx;
			border-radius: 50%;
			overflow: hidden;
			image{
				width: 100%;
				height: 100%;
			}
		}
		.title{
			font-size: 44rpx;
			color: #333;
		}
	}
	.login-form{
		margin: 20rpx 0;
		padding: 0 50rpx;
		.tip{
			width: 100%;
			height: auto;
			padding-left: 30rpx;
			color: #FF4D4F;
		}
		.uni-form-item{
			height: 100rpx;
			margin: 30rpx 0 0 0;
			.phone,.password{
				width: 100%;
				background-color: #fff;
				border-radius: 50px;
				height: 100rpx;
				display: flex;
				justify-content: left;
				align-items: center;
				padding:0 30rpx;
				input{
					margin-left: 20rpx;
				}
			}
			&.vertify-box{
				display: flex;
				justify-content: space-between;
				align-items: center;
				.vertify{
					width: 100%;
					background-color: #fff;
					border-radius: 50px;
					height: 100rpx;
					display: flex;
					justify-content: left;
					align-items: center;
					padding:0 30rpx;
					input{
						margin-left: 20rpx;
					}
				}
				.vcode-btn{
					width: 400rpx;
					font-size: 15px;
					margin-left: 10rpx;
					height: 80rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					color: #FF4D4F;
					border:2px #FF4D4F solid;
				}
			}
		}
		.login-btn{
			margin-top: 60rpx;
			width: 100%;
			height: 80rpx;
			background-color: #FF4D4F;
			color: #fff;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 40rpx;
			letter-spacing: 20rpx;
		}
	}
}

</style>
